//
//  SXRefreshControl.swift
//  sina
//
//  Created by shengxinwei on 16/5/27.
//  Copyright © 2016年 shengxinwei. All rights reserved.
//

import UIKit
import SnapKit

private let refHeight: CGFloat = 60

enum RefreshStatue {
    case Normal //普通状态
    case Pulling //准备起飞状态 .,准备刷新状态
    case Refreshing //刷新状态
}

class SXRefreshControl: UIControl {

    var status: RefreshStatue = .Normal {
        didSet {
            switch status {
            case .Normal:
                
                indicatorView.hidden = true
                arrowicon.hidden = false
                indicatorView.stopAnimating()
                tipLabel.text = "下拉起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformIdentity
                })
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { 
                        var inset = self.scrollView!.contentInset
                        inset.top -= refHeight
                        self.scrollView?.contentInset = inset
                    })
                }
                
            case .Pulling:
                tipLabel.text = "准备起飞"
                UIView.animateWithDuration(0.25, animations: { 
                    self.arrowicon.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                
                
            case .Refreshing:
                
                arrowicon.hidden = true
                tipLabel.text = "正在起飞"
                indicatorView.startAnimating()
                
                 //请求网络数据 给观察的对象主动发送对应类型的事件
                sendActionsForControlEvents(.ValueChanged)
                UIView.animateWithDuration(0.25, animations: { 
                    
                    var inset = self.scrollView!.contentInset
                    inset.top += refHeight
                    self.scrollView?.contentInset = inset
                })
                //创造悬停的效果

            }
        }
    }

    override init(frame: CGRect) {
        let rect = CGRect(x: 0, y: -refHeight, width: ScreenWidth, height: refHeight)
        super.init(frame: rect)
        self.backgroundColor = UIColor.yellowColor()
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func endRefreshin() {
        status = .Normal
    }
    
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        let myFater = newSuperview as? UIScrollView
        if (myFater != nil) {
            scrollView = myFater
            //通过kvo键值观察对象的变化
            scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .New, context: nil)
        }
    }
    
    //实现观察方法 ..如果不实现观察方法,系统会奔溃
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        let offsetY = scrollView?.contentOffset.y ?? 0
        if scrollView!.dragging {
            if status == .Pulling && offsetY > -124 {
                //改为普通状态
                status = .Normal
            } else if status == .Normal && offsetY < -124 {
                //准备起飞状态
                status = .Pulling
            }
        } else {
            //当时准备起飞状态,,没有抓举的情况下,状态改为刷新状态
            if status == .Pulling {
                status = .Refreshing
            }
            
        }
        
        
    }
    
    func setupUI() {
        addSubview(arrowicon)
        addSubview(tipLabel)
        addSubview(indicatorView)
        
        arrowicon.snp_makeConstraints { (make) in
            make.centerX.equalTo(self.snp_centerX).offset(-30)
            make.centerY.equalTo(self.snp_centerY)
        }
        tipLabel.snp_makeConstraints { (make) in
            make.centerY.equalTo(self.snp_centerY)
            make.left.equalTo(arrowicon.snp_right)            
        }
        indicatorView.snp_makeConstraints { (make) in
            make.center.equalTo(arrowicon.snp_center)
        }
    }
    
    
    
    
    var scrollView: UIScrollView?
    //TODO: 懒加载
    private lazy var arrowicon: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    private lazy var tipLabel: UILabel = {
        let lab = UILabel()
        lab.text = "下拉起飞"
        lab.textColor = UIColor.darkGrayColor()
        lab.font = UIFont.systemFontOfSize(14.0)
        return lab
    }()
    
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .Gray)

    //移除键值观察者.必须移除
    deinit {
        scrollView?.removeObserver(self, forKeyPath: "contenOffset")
    }

}
